<?php

// +---------------------------------------------------
// | Name：星空框架 快递公司规则验证
// +---------------------------------------------------
// | Version: V5.0
// +---------------------------------------------------
// | Author: xkyinzhe <zhonghuaxinxing@sina.cn>
// +---------------------------------------------------
// | Time: 2021-04-21 09:26
// +---------------------------------------------------
declare(strict_types=1);

namespace app\common\validate;

use app\common\model\Shipping as ShippingModel;
use think\Validate;

/**
 * @xk 快递公司规则验证
 */
class Shipping extends Validate
{
    protected $rule = [
    'shipping_id' => 'number|min:1',
    'company_name' => 'require|min:2|max:100',
    'company_code' => 'require', //不允许出现负数
    'company_code' => 'checkCode',
    'order_id' => 'number|min:0',
    'status' => 'in:0,1',
  ];
    protected $message = [
    'shipping_id.number' => '请选择需要操作的数据',
    'company_name.require' => '请填写快递公司名称',
    'company_code.number' => '请填写快递公司编码',
    'company_code.checkCode' => '快递公司编码已经存在',
    'order_id.number' => '请按照规则填写排序ID',
    'status' => '菜单状态不合法',
  ];
    protected $scene = [
    'create' => ['company_name', 'company_code', 'order_id', 'status'],
    'edit' => ['shipping_id', 'company_name', 'company_code', 'order_id', 'status']
  ];

    protected function checkCode($value)
    {
        $shippingModel = new ShippingModel();
        $param = request()->param();
        $act = isset($param['act']) ? $param['act'] : 'company_code';
        $condition = [];
        $condition[] = ['company_code', '=', $value];
        switch ($act) {
          case 'create':
            $count = $shippingModel->where($condition)->count();
            if ($count > 0) {
                return false;
            }

            return true;
            break;
          case 'edit':
            $shipping_id = $shippingModel->where($condition)->value('shipping_id');
            if ($shipping_id <= 0) {
                return true;
            }
            if ($shipping_id == $param['shipping_id']) {
                return true;
            }

            return false;
            break;
      }
    }
}
